﻿using HandyControl.Controls;
using MyHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using clf.weighing.entity;
using Brushes = System.Windows.Media.Brushes;
using Button = System.Windows.Controls.Button;
using CheckBox = System.Windows.Controls.CheckBox;
using Binding = System.Windows.Data.Binding;
using System.Windows.Threading;
using System.Collections.ObjectModel;

namespace weighing
{
    /// <summary>
    /// OrtherDataUC.xaml 的交互逻辑
    /// </summary>
    public partial class OrtherDataUC : System.Windows.Controls.UserControl
    {
        private bool IsDataLoading =false;
        private WeighingBillVo? mWeighingBillVo;
        private ObservableCollection<WeighingBillVo> mWeihingBillVos = new ObservableCollection<WeighingBillVo>();

        private DispatcherTimer? mTimer;
        #region property
        public WeightingBillType BillType
        {
            get { return (WeightingBillType)GetValue(BillTypeProperty); }
            set { SetValue(BillTypeProperty, value); }
        }
        public static readonly DependencyProperty BillTypeProperty =
            DependencyProperty.Register("BillType", typeof(WeightingBillType), typeof(OrtherDataUC), new PropertyMetadata(WeightingBillType.UNKNOWN));

        #endregion
        public OrtherDataUC()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this)) return;
        }

        #region loaded 
        private void Orther_Data_Content_Loaded(object sender, RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this)) return;

            this.DataGrid.ItemsSource = mWeihingBillVos;

            //根据配制显示或隐藏列
            ShowOrHideColumns();

            CreateBackupFieldUi(this.DataGrid);

            if (this.IsVisible && Visibility == Visibility.Visible)
            {
                LoadData();
            }

            DelegeteFactory.Instance.onWeighingDataChanged += OnWeighingDataChangedHandle;

            InitTimer();

            mTimer?.Start();
        }

        private void Orther_Data_Content_Unloaded(object sender, RoutedEventArgs e)
        {
            mTimer?.Stop();
        }

        private void Orther_Data_Content_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.IsVisible && Visibility == Visibility.Visible)
            {
                LoadData();

                mTimer?.Start();
            }
            else
            {
                mTimer?.Stop(); 
            }
        }
        #endregion

        #region  Refresh data Timer
        private void InitTimer()
        {
            int interval = App.Config.SystemConfig.DataRefreshInterval;
            if (interval <= 0)
            {
                return;
            }
            mTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(interval)
            };
            mTimer.Tick += (obj, eventArgs) =>
            {
                if (this.IsVisible == true && this.Visibility == Visibility.Visible)
                {
                    this.Dispatcher.Invoke(() => { LoadData(); });
                }
            };
        }
        #endregion

        public void LoadData()
        {
            if (IsDataLoading || this.IsVisible == false) return;
            if (DesignerProperties.GetIsInDesignMode(this)) return;
            IsDataLoading = true;
            mWeihingBillVos.Clear();
            var list = WeighingBillDao.Instance.GetTodayBills(BillType);
            list?.ForEach((i) => mWeihingBillVos.Add(new WeighingBillVo(i)));
            this.allCb.IsChecked = true;
            IsDataLoading = false;
        }

        #region datagrid event

        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ChangeDataColor(e);
        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.DataGrid.SelectedItem is WeighingBillVo vo)
            {
                mWeighingBillVo = vo;

                if (mWeighingBillVo.Status == 1)
                {
                    OpenDetail();
                }
                else
                {
                    string msg = $"是否要对 {mWeighingBillVo.CarNumber} 进行 出场过磅，\r\n 请认真核对车牌号,减少出错？";
                    var result = CommonFunction.Ask(msg);
                    if (result ==  MessageBoxResult.Yes)
                    {
                        if(BillType == WeightingBillType.Mixture)
                        {
                            DelegeteFactory.Instance.onSimpleWeighingSelectOutData?.Invoke(mWeighingBillVo.mWeighingBill);
                        }
                        else
                        {
                            //OrtherWeighingWindow ow = this.Tag as OrtherWeighingWindow;
                            //if (ow != null)
                            //{
                            //    ow.otherWeighingUc.mWeighingBill = vo.mWeighingBill;
                            //    ow.otherWeighingUc.BuildCurrWeighingBill();
                            //}
                            //else
                            //{
                            //    Growl.Info("不能操作", "main");
                            //}
                            Growl.Info("不能操作", "main");
                        }
                       
                    }
                }
            }
            else { mWeighingBillVo = null; }
        }

        private void DataGrid_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
                if (this.DataGrid.SelectedItem is WeighingBillVo bill)
                {
                    if (bill.Status == 0 && (App.CurrentUser.roleType == (int)UserRoleType.WeighingManager || App.CurrentUser.roleType == (int)UserRoleType.Developer))
                    {
                        DeleteBill(bill.mWeighingBill);
                    }
                }
        }
        #endregion

        public void ChangeDataColor(DataGridRowEventArgs eventArgs)
        {
            eventArgs.Row.Header = eventArgs.Row.GetIndex() + 1;
            if (eventArgs.Row.DataContext is WeighingBillVo bill)
            {
                eventArgs.Row.ToolTip = "双击查看详情";
                if (bill.Status == 0)
                {
                    eventArgs.Row.Foreground = Brushes.Red;
                    eventArgs.Row.ToolTip = "双击进行出场过磅";
                }
                else
                {
                    eventArgs.Row.Foreground = Brushes.Black;                  
                }
            }
        }
        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                    DeleteBill(bill.mWeighingBill);
                }
            }
        }

        private void DeleteBill(WeighingBill bill)
        {
            var result = CommonFunction.Ask($"是否要删除编号为 {bill.number} 的过磅数据？");
            if (result == MessageBoxResult.Yes)
            {
                this.DeleteReasonPopup.Tag = bill.number; //将 编号 进行传递
                this.DeleteReasonPopup.IsOpen = true;
            }
        }

        #region popup delete reason  弹窗删除
        private void PopupCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.DeleteReasonPopup.IsOpen = false;
        }

        private void PopupDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            string reason = this.DeleteReasonCb.Text.Trim();
            if (reason.Length < 5)
            {
                CommonFunction.AlertInfo("请选择或者输入删除该数据的原因，5个字以上");
                return;
            }
            this.DeleteReasonPopup.IsOpen = false;
            string number = this.DeleteReasonPopup.Tag.ToString();
            if (string.IsNullOrEmpty(number))
            {
                Growl.Info("删除失败！", "main");
                return;
            }
            bool res = WeighingBillDao.Instance.SoftDelete(number, reason);
            if (res)
            {
                LoadData();
                Growl.Success($"{number} 删除成功", "main");
            }
            else
            {
                Growl.Error($"{number} 删除失败", "main");
            }
        }
        private void DeleteReasonPopup_Closed(object sender, EventArgs e)
        {
            this.DeleteReasonCb.SelectedIndex = -1;
            this.DeleteReasonCb.Text = "";
        }

        #endregion

        private void OpenDetail()
        {
            this.DrawerHeaderTb.Text = mWeighingBillVo?.Number + " 磅单详情";
            this.detailRootBorder.Content = null;
            StackPanel panel = new StackPanel();
            var uc = new OrtherPrintUc() { DataContext = mWeighingBillVo };
            panel.Children.Add(uc);
            var img = new BillImageUC(mWeighingBillVo?.mWeighingBill);
            panel.Children.Add(img);
            this.detailRootBorder.Content = panel;
            this.DrawerBottom.IsOpen = true;
        }


        #region 动态显示列

        protected void ShowOrHideColumns()
        {
            var dg = this.DataGrid;
            string name = GetColumnsName();

            var dic = DataGridColumnsHelper.GetByName(name);

            var columns = dg.Columns;

            if (dic.Count == 0)
            {
                foreach (var c in columns)
                {
                    if (c is DataGridTextColumn tc)
                    {
                        string header = tc.Header.ToString();
                        if (dic.Keys.Contains(header))
                        {
                            dic[header] = true;
                        }
                        else
                        {
                            dic.Add(header, true);
                        }
                    }
                }

                DataGridColumnsHelper.Save(name, dic);
            }
            else
            {
                foreach (var c in columns)
                {
                    if (c is DataGridTextColumn tc)
                    {
                        string header = tc.Header.ToString();
                        if (dic.Keys.Contains(header))
                        {
                            if (dic[header] == true)
                            {
                                tc.Visibility = Visibility.Visible;
                            }
                            else
                            {
                                tc.Visibility = Visibility.Collapsed;
                            }
                        }
                        else
                        {
                            tc.Visibility = Visibility.Collapsed;
                        }
                    }
                }
            }
        }

        private Dictionary<Int32, CheckBox> columnsDics;
        private void ColumnsSettingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (columnsDics == null)
            {
                columnsDics = new Dictionary<int, CheckBox>();
                var cols = this.DataGrid.Columns;
                var style = FindResource("CheckBoxBaseStyle") as Style;
                for (int i = 0; i < cols.Count; i++)
                {
                    var col = cols[i];
                    var cb = new CheckBox()
                    {
                        Style = style,
                        Content = col.Header,
                        HorizontalAlignment =System.Windows. HorizontalAlignment.Left,
                        Tag = i,
                        Margin = new Thickness(20, 5, 20, 5),
                    };
                    if (col.Visibility == Visibility)
                    {
                        cb.IsChecked = true;
                    }
                    else
                    {
                        cb.IsChecked = false;
                    }
                    cb.Checked += ColumnCheckBox_Checked;
                    cb.Unchecked += ColumnCheckBox_Unchecked;
                    columnsDics.Add(i, cb);
                }
                foreach (var item in columnsDics)
                {
                    this.columnsPanel.Children.Add(item.Value);
                }
            }
            this.columnPopup.IsOpen = !columnPopup.IsOpen;
        }
        private void ColumnCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox cb)
            {
                var index = (int)cb.Tag;
                var col = this.DataGrid.Columns[index];
                if (col != null)
                {
                    col.Visibility = Visibility.Visible;

                    string header = cb.Content.ToString();
                    SaveColumnSetting(header, true);
                }
            }
        }

        private void ColumnCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox cb)
            {
                var index = (int)cb.Tag;
                var col = this.DataGrid.Columns[index];
                if (col != null)
                {
                    col.Visibility = Visibility.Collapsed;

                    string header = cb.Content.ToString();
                    SaveColumnSetting(header, false);
                }
            }
        }

        protected void SaveColumnSetting(string header, bool isShow)
        {
            string name = GetColumnsName();

            DataGridColumnsHelper.Save(name, header, isShow);
        }

        private string GetColumnsName()
        {
            string res = "";
            switch (BillType)
            {
                case WeightingBillType.Buy:
                    res = DataGridColumnsHelper.reportBuy;
                    break;
                case WeightingBillType.Sale:
                    res = DataGridColumnsHelper.reportSale;
                    break;
                case WeightingBillType.Self:
                    res = DataGridColumnsHelper.reportSelf;
                    break;
                case WeightingBillType.Foreign:
                    res = DataGridColumnsHelper.reportforegin;
                    break;
                case WeightingBillType.Mixture:
                    res = DataGridColumnsHelper.mixture;
                    break;
            }
            return res;
        }

        #endregion

        /// <summary>
        /// 过虑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBar_OnSearchStarted(object sender, HandyControl.Data.FunctionEventArgs<string> e)
        {
            string key = this.searcher.Text.Trim();
            Console.WriteLine("--" + key);
            var temp = new List<WeighingBillVo>();
            if (!string.IsNullOrEmpty(key))
            {
                ConsoleHelper.log("serach");
                foreach (WeighingBillVo vo in mWeihingBillVos)
                {
                    if (vo.CarNumber.Contains(key) 
                        || vo.MaterialName.Contains(key) 
                        || vo.SendCompanyName.Contains(key) 
                        || vo.ReceiveCompanyName.Contains(key))
                    {
                        temp.Add(vo);
                    }
                }
                if (temp.Count > 0)
                {
                    this.DataGrid.ItemsSource = temp;
                }
                else
                {
                    Growl.Info("没有过虑到任何数据，请换个关键字", "main");
                }
            }
            else
            {
                this.DataGrid.ItemsSource = null;
                this.DataGrid.ItemsSource = mWeihingBillVos;
            }
        }

        private void Searcher_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.searcher.Text))
            {
                this.DataGrid.ItemsSource = null;
                this.DataGrid.ItemsSource = mWeihingBillVos;
            }
        }

        #region data Filler

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded)
            {
                if (sender is CheckBox checkBox)
                {
                    if (checkBox.Name == "allCb")
                    {
                        this.noOutCb.IsChecked = false;
                        this.outCb.IsChecked = false;
                        this.noPrintCb.IsChecked = false;
                    }
                    else
                    {
                        this.allCb.IsChecked = false;
                    }
                }
                FilerData();
            }
        }


        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (this.allCb.IsChecked == false) FilerData();
        }
        /// <summary>
        /// 过虑 已经已经显示的数据
        /// </summary>
        private List<WeighingBillVo> tempBillVos = new List<WeighingBillVo>();
        private void FilerData()
        {
            if (IsDataLoading) return;
            if (this.allCb.IsChecked == true)
            {
                this.DataGrid.ItemsSource = null;
                this.DataGrid.ItemsSource = mWeihingBillVos;
            }
            else
            {
                tempBillVos.Clear();
                foreach (var item in mWeihingBillVos)
                {

                    if (this.noOutCb.IsChecked == true)
                    {
                        if (item.Status == 0)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.outCb.IsChecked == true)
                    {
                        if (item.Status == 1)
                        {
                            tempBillVos.Add(item);
                        }
                    }

                    if (this.noPrintCb.IsChecked == true)
                    {
                        if (item.PrintTimes == 0)
                        {
                            tempBillVos.Add(item);
                        }
                    }
                }
                if (tempBillVos.Count > 0)
                {
                    this.DataGrid.ItemsSource = null;
                    this.DataGrid.ItemsSource = tempBillVos;
                }
                else
                {
                    Growl.Info("没有匹配的数据，显示所有数据");
                    this.allCb.IsChecked = true;
                }
            }
        }
        #endregion

        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                    if (App.Config.BillPrintConfig.IsUserExclCustomBill)
                    {

                        new PrintEXCLWindow(bill.Id)
                        {
                            Owner = App.Current.MainWindow
                        }.ShowDialog();
                    }
                    else
                    {
                        new PrintWindow(bill.Id, WeightingBillType.WeighintBill)
                        {
                            Owner = App.Current.MainWindow
                        }.ShowDialog();
                    }
                }
            }
        }
        //取消出场操作
        private void RepetitionOutBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button bt)
            {
                if (bt.Tag is WeighingBillVo bill)
                {
                   var result = CommonFunction.Ask($"是否要取消编号为 {bill.Number} 的过磅数据出场操作？此操作需要谨慎");

                    if (result == MessageBoxResult.Yes)
                    {
                        string msg = "操作成功！只改变数据的状态，未改变数据原来过磅的值，再次出场时会覆盖原来的值";

                        int res =WeighingBillDao.Instance.ChangeStatus(bill.Number, BillStatus.NoOut);
                        if (res > 0)
                        {
                            Growl.Success(msg);
                            LoadData();
                            Log.Info($"用户：{App.CurrentUser.name} 在 {DateTimeHelper.getCurrentDateTime()} 将磅单编号为 {bill.Number} 取消出场");
                        }
                        else
                        {
                            msg = "操作失败！";
                            Growl.Success(msg);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailBtn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button btn)
            {
                if (btn.Tag is WeighingBillVo bill)
                {
                    mWeighingBillVo = bill;
                    OpenDetail();
                }
                else { mWeighingBillVo = null; }
            }
        }

        private void OnWeighingDataChangedHandle(WeightingBillType billType)
        {
            if (billType != this.BillType) return;
            LoadData();
        }


        // to edit
        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            WeighingBillVo vo = btn?.Tag as WeighingBillVo;
            if (BillType == WeightingBillType.Mixture)
            {
                new BillEditSimpleWindow(vo)
                {
                    Owner = App.Current.MainWindow,                 
                }.ShowDialog();
            }
            else
            {               
                if (vo != null)
                {
                    new BillEditWindow(vo)
                    {
                        Owner = App.Current.MainWindow,
                        OnChanged = (res) => { if (res) LoadData(); }
                    }.ShowDialog();
                }
            }
           
        }

        #region 备用字段
        private void BackfiledBtn_Click(object sender, RoutedEventArgs e)
        {
            new AddBackupFieldWin()
            {
                BillType = WeightingBillType.Mixture,
                Owner = App.Current.MainWindow,
            }.Show();
        }


        /// <summary>
        /// 动态设置备用字段的列
        /// </summary>
        protected void CreateBackupFieldUi(DataGrid dataGrid)
        {
            int type = (int)this.BillType;

            List<BackupBillField> fields = BackupBillFieldDao.Instance.SelectAllByType(type);

            if (fields == null || fields.Count == 0) return;

            for (int i = 0; i < fields.Count; i++)
            {
                BackupBillField item = fields[i];
                if (item.isEnable == 1 && item.isShow == 1)
                {
                    DataGridTextColumn column = new DataGridTextColumn
                    {
                        Header = item.displayName,
                        Binding = new Binding(StringHelper.DBNamingToCamelCase(item.fiedName, true)),
                    };
                    InfoElement.SetTitle(column, item.fiedName);
                    int index = dataGrid.Columns.Count - 1;
                    dataGrid.Columns.Insert(index, column);
                }
            }
        }

        #endregion

        
    }
}
